package start.demo01.email;

import lombok.SneakyThrows;
import org.junit.Test;

import javax.mail.*;
import javax.mail.event.MessageCountAdapter;
import javax.mail.event.MessageCountEvent;
import javax.mail.internet.MimeMessage;
import javax.mail.search.*;
import java.util.Date;
import java.util.Properties;

public class IMAPStore2 {

    private static String pop3Server = "pop.qq.com";
    private static String protocol = "imap";
    private static String username = "790867216@qq.com";
    private static String password = "khmkygxoiexvbfgf"; //

    @Test
    public void t0() throws Exception {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", protocol);
        props.setProperty("mail.smtp.host", pop3Server);
        Session session = Session.getDefaultInstance(props);
        session.setDebug(false);
        Store store = session.getStore(protocol);
        store.connect(pop3Server, username, password);
        System.out.println("start开始");
    }

    private static void start(Store store) throws Exception {
        Folder folder = store.getFolder("INBOX");//
        folder.open(Folder.READ_WRITE); //
        long millis = System.currentTimeMillis();
//        Message[] messages = searchMails(folder, millis - 1000 * 60*60*24, millis);//
        folder.addMessageCountListener(new MessageCountAdapter() {
            @SneakyThrows
            @Override
            public void messagesAdded(MessageCountEvent e) {
                Message[] messages = e.getMessages();
                for (Message message : messages) {
                    String subject = message.getSubject();//
                    Address from = message.getFrom()[0];//
                    System.out.println("获取邮件 " + subject + "\t " + from);
//                    message.writeTo(System.out);//
                    //设置已读
                    message.setFlag(Flags.Flag.SEEN, true);
                }
            }
        });
//        for (Message message : messages) {
//            String subject = message.getSubject();//
//            Address from = message.getFrom()[0];//
//            System.out.println(" " + subject + "\t " + from);
//            message.writeTo(System.out);//
//        }
        folder.close(false);
    }

    /**
     * @param folder
     * @throws Exception
     */
    private static Message[] searchMails(Folder folder, long start, long end) throws Exception {
        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); //false true

        SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, new Date(start));
        SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, new Date(end));
//        FromStringTerm fromStringTerm = new FromStringTerm("???");
        SearchTerm andTerm = new AndTerm(new SearchTerm[]{comparisonTermGe,
                comparisonTermLe, ft});
        Message[] messages = folder.search(andTerm); // message
        return messages;
    }
}
